package game.module.ddz.logic;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.RandomUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import game.entity.PlayingRole;
import game.lan.msg.DdzStart2HsMessage;
import game.module.ddz.DdzConstants;
import game.module.ddz.bean.DdzLanPlayerInfo;
import game.module.ddz.bean.DdzRound;
import game.module.user.dao.LanSessionCache;
import game.session.SessionManager;
import io.netty.channel.Channel;
import lion.common.ArrayUtility;
import lion.math.RandomDispatcher;
import lua.LuaMessageDdz.PushDdzNewRound;

public class DdzLogic {

	private static Logger logger = LoggerFactory.getLogger(DdzLogic.class);

	static class SingletonHolder {
		static DdzLogic instance = new DdzLogic();
	}

	public static DdzLogic getInstance() {
		return SingletonHolder.instance;
	}

	public void ddzStart(Channel channel, String roomId, List<DdzLanPlayerInfo> playerList, short roundSum, byte jiaoOrQiang) {
		logger.info("ddz start,playerList={},roundSum={}", playerList, roundSum);
		int playerCount = playerList.size();
		DdzRound ddzRound = new DdzRound();
		ddzRound.setRoundSum(roundSum);
		ddzRound.setJiaoFenOrQiang(jiaoOrQiang);// 1叫分，2抢地主
		randCard(ddzRound);
		ddzRound.setRoomUuid(roomId);
		ddzRound.setRoundCount(1);
		DdzStart2HsMessage respMsg = new DdzStart2HsMessage(channel.alloc());
		respMsg.writeString(roomId);
		respMsg.writeInt(playerCount);
		for (int i = 0; i < playerCount; i++) {
			int playerId = playerList.get(i).getPlayerId();
			List<Byte> aPlayerCards = ddzRound.getCards().get(i);
			respMsg.writeInt(playerId);
			respMsg.writeInt(aPlayerCards.size());
			for (Byte aCard : aPlayerCards) {
				respMsg.writeByte(aCard);
			}
		}
		List<Byte> diList = ddzRound.getDi();
		respMsg.writeInt(diList.size());
		for (Byte aCard : diList) {
			respMsg.writeByte(aCard);
		}
		// 叫地主的index
		int jiaoDiZhuIndex = RandomUtils.nextInt(0, 3);
		ddzRound.setJiaoDiZhuIndex(jiaoDiZhuIndex);
		ddzRound.setLoopCount(0);
		respMsg.writeInt(jiaoDiZhuIndex);
		// 缓存玩家信息
		List<Integer> playerIds = new ArrayList<>();
		ddzRound.setPlayerIds(playerIds);
		for (DdzLanPlayerInfo ddzLanPlayerInfo : playerList) {
			LanSessionCache.getInstance().addSession(ddzLanPlayerInfo.getSessionId(), ddzLanPlayerInfo.getPlayerId());
			playerIds.add(ddzLanPlayerInfo.getPlayerId());
		}
		// 缓存牌局信息
		for (DdzLanPlayerInfo ddzLanPlayerInfo : playerList) {
			DdzDataManager.getInstance().addRoundCache(ddzLanPlayerInfo.getPlayerId(), ddzRound);
		}
		long create_time = System.currentTimeMillis() / 1000;
		ddzRound.setCreate_time((int) create_time);
		channel.writeAndFlush(respMsg);
	}

	public void randCard(DdzRound ddzRound) {
		RandomDispatcher<Byte> rd = new RandomDispatcher<>();
		for (short i = 0; i < DdzConstants.cardData.length; i++) {
			rd.put(1, DdzConstants.cardData[i]);
		}
		List<List<Byte>> cards = new ArrayList<>();
		ddzRound.setCards(cards);
		for (int i = 0; i < 3; i++) {
			List<Byte> aPlayerCards = new ArrayList<>();
			for (int j = 0; j < 17; j++) {
				aPlayerCards.add(rd.randomRemove());
			}
			cards.add(aPlayerCards);
		}
		// di pai
		List<Byte> dis = new ArrayList<>();
		ddzRound.setDi(dis);
		for (int i = 0; i < 3; i++) {
			dis.add(rd.randomRemove());
		}
	}

	public void nextRound(DdzRound ddzRound) {
		randCard(ddzRound);
		// 叫地主的index
		int jiaoDiZhuIndex = RandomUtils.nextInt(0, 3);
		ddzRound.setJiaoDiZhuIndex(jiaoDiZhuIndex);
		ddzRound.setRoundCount(ddzRound.getRoundCount() + 1);
		ddzRound.setLoopCount(0);
		ddzRound.setLastJiaoScore(null);
		ddzRound.setLastJiaoIndex(null);
		ddzRound.setDiZhuIndex(null);
		ddzRound.setChuPaiIndex(null);
		ddzRound.setValid_chuPai(null);
		ddzRound.setValidChupaiIndex(null);
		// 抢地主处理
		ddzRound.setQiangDiZhuIndex(null);
		ddzRound.setJiaBei(false);
		Set<Byte> cancelQiangSet = ddzRound.getCancelQiangSet();
		if (cancelQiangSet != null) {
			cancelQiangSet.clear();
		}
		Set<Byte> cancelFanQiangSet = ddzRound.getCancelFanQiangSet();
		if (cancelFanQiangSet != null) {
			cancelFanQiangSet.clear();
		}
		Map<Integer, Integer> jiabeiMap = ddzRound.getJiaBeiMap();
		if (jiabeiMap != null) {
			jiabeiMap.clear();
		}
		Map<Integer, Integer> chupaiCount = ddzRound.getChuPaiCount();
		if (chupaiCount != null) {
			chupaiCount.clear();
		}
		// push
		PushDdzNewRound pushMsg = new PushDdzNewRound();
		// 发送消息
		List<Integer> playerIds = ddzRound.getPlayerIds();
		int playerIndex = 0;
		for (Integer aPlayerId : playerIds) {
			// 推送
			PlayingRole pr = SessionManager.getInstance().getPlayer(aPlayerId);
			if (pr != null && pr.isChannelActive()) {
				List<Byte> cardList = ddzRound.getCards().get(playerIndex++);
				pushMsg.my_cards = ArrayUtility.toByteArray(cardList);
				pushMsg.jiao_dizhu_index = ddzRound.getJiaoDiZhuIndex().shortValue();
				pr.writeAndFlush(pushMsg.build(pr.alloc()));
			}
		}
	}

	public void roundOver(DdzRound ddzRound) {
		List<Integer> players = ddzRound.getPlayerIds();
		for (Integer aPlayerId : players) {
			DdzDataManager.getInstance().removePlayer(aPlayerId);
		}
	}

}
